<?php

/**
 * 文档章节模型
 *
 * @author 煤老板 <meok23@sina.com>
 * @date   2017-06-16
 */

namespace app\common\model;

use fw\db\DB;
use fw\tool\Request;

class Chapter
{
    /**
     * 获取一条数据
     *
     * @param array $args
     *
     * @return array
     */
    public function getInfo($args)
    {
        // 参数获取
        $chapter_id = (int)Request::input($args, 'chapter_id');
        $doc_id = (int)Request::input($args, 'doc_id');

        $ret = [];
        if ($chapter_id > 0) {
            $ret = DB::table('chapter')->where('chapter_id=:chapter_id', [':chapter_id' => $chapter_id])->selectRow();
        } elseif ($doc_id > 0) {
            $ret = DB::table('chapter')->where('doc_id=:doc_id', [':doc_id' => $doc_id])->order('sort')->selectRow();
        }

        return $ret;
    }

    /**
     * 获取列表或统计条数
     *
     * @param array $args
     *
     * @return array|int
     */
    public function getList($args)
    {
        // 参数获取
        $chapter_ids = Request::input($args, 'chapter_ids', 'trim');
        $doc_id = (int)Request::input($args, 'doc_id');

        $page = Request::input($args, 'page', 'intval', 1);
        $length = Request::input($args, 'length', 'intval', 100);

        $sort_way = Request::input($args, 'sort_way', 'trim', 'DESC');
        $sort_way = strtoupper($sort_way);

        $is_count = Request::input($args, 'is_count', 'boolval', false);

        // 条件组装
        $prep = $map = [];
        if (!empty($chapter_ids)) {
            $map[] = 'chapter_id IN (:chapter_id)';
            $prep[':chapter_id'] = $chapter_ids;
        }
        if ($doc_id != 0) {
            $map[] = 'doc_id=:doc_id';
            $prep[':doc_id'] = $doc_id;
        }
        $where = implode(' AND ', $map);

        // 查询条数
        if ($is_count === true) {
            return DB::table('chapter')->where($where, $prep)->count();
        }

        // 查询列表
        $rows = DB::table('chapter')
            ->where($where, $prep)
            ->order('sort ' . $sort_way)
            ->limit(($page - 1) * $length . ',' . $length)
            ->select();

        return $rows;
    }
}
